<template>
  <div class="invoice-edit-container">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      :disabled="loading"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="发票号码" prop="invoiceNumber">
            <el-input v-model="formData.invoiceNumber" placeholder="请输入发票号码" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="发票代码" prop="invoiceCode">
            <el-input v-model="formData.invoiceCode" placeholder="请输入发票代码" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="发票类型" prop="invoiceTypeCode">
            <el-select v-model="formData.invoiceTypeCode" placeholder="请选择发票类型" style="width: 100%">
              <el-option label="增值税专用发票" value="special" />
              <el-option label="增值税普通发票" value="normal" />
              <el-option label="电子发票" value="electronic" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="是否红字发票" prop="isRedInvoice">
            <el-radio-group v-model="formData.isRedInvoice">
              <el-radio label="Y">是</el-radio>
              <el-radio label="N">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="开票日期" prop="invoiceDate">
            <el-date-picker
              v-model="formData.invoiceDate"
              type="date"
              placeholder="请选择开票日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="供应商" prop="supplierId">
            <el-select v-model="formData.supplierId" placeholder="请选择供应商" style="width: 100%">
              <el-option label="杭州华采供应链有限公司" value="1" />
              <el-option label="浙江医药股份有限公司" value="2" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="销方识别号" prop="sellerTaxNumber">
            <el-input v-model="formData.sellerTaxNumber" placeholder="请输入销方识别号" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="销方名称" prop="sellerName">
            <el-input v-model="formData.sellerName" placeholder="请输入销方名称" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="购方识别号" prop="buyerTaxNumber">
            <el-input v-model="formData.buyerTaxNumber" placeholder="请输入购方识别号" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="购方名称" prop="buyerName">
            <el-input v-model="formData.buyerName" placeholder="请输入购方名称" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="金额" prop="totalAmount">
            <el-input-number
              v-model="formData.totalAmount"
              placeholder="请输入金额"
              :precision="2"
              :step="100"
              :min="0"
              controls-position="right"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="税额" prop="taxAmount">
            <el-input-number
              v-model="formData.taxAmount"
              placeholder="请输入税额"
              :precision="2"
              :step="10"
              :min="0"
              controls-position="right"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="价税合计" prop="totalTaxAmount">
            <el-input-number
              v-model="formData.totalTaxAmount"
              placeholder="请输入价税合计"
              :precision="2"
              :step="100"
              :min="0"
              controls-position="right"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="开票人" prop="issuer">
            <el-input v-model="formData.issuer" placeholder="请输入开票人" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="税务机关代码" prop="taxBureauCode">
            <el-input v-model="formData.taxBureauCode" placeholder="请输入税务机关代码" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="税务机关名称" prop="taxBureauName">
            <el-input v-model="formData.taxBureauName" placeholder="请输入税务机关名称" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="formData.remark"
          type="textarea"
          :rows="3"
          placeholder="请输入备注信息"
        />
      </el-form-item>
      
      <!-- 操作按钮 -->
      <div class="form-actions">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading">保存</el-button>
      </div>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, defineProps, defineEmits } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getIncomingInvoiceById, createIncomingInvoice, updateIncomingInvoice } from '@/api/invoice'

// 定义props
const props = defineProps({
  operation: {
    type: String as () => 'add' | 'edit' | 'view',
    default: 'add'
  },
  invoiceId: {
    type: [String, Number],
    default: null
  }
})

// 定义emits
const emit = defineEmits(['save-success', 'cancel'])

// 路由
const route = useRoute()
const router = useRouter()

// 是否为编辑模式
const isEdit = ref(false)

// 加载状态
const loading = ref(false)

// 表单引用
const formRef = ref()

// 表单数据
const formData = reactive({
  id: '',
  invoiceNumber: '',
  invoiceCode: '',
  invoiceTypeCode: '',
  isRedInvoice: 'N',
  invoiceDate: '',
  supplierId: '',
  sellerTaxNumber: '',
  sellerName: '',
  buyerTaxNumber: '',
  buyerName: '',
  totalAmount: 0,
  taxAmount: 0,
  totalTaxAmount: 0,
  issuer: '',
  taxBureauCode: '',
  taxBureauName: '',
  remark: ''
})

// 表单验证规则
const formRules = {
  invoiceNumber: [
    { required: true, message: '请输入发票号码', trigger: 'blur' }
  ],
  invoiceCode: [
    { required: true, message: '请输入发票代码', trigger: 'blur' }
  ],
  invoiceTypeCode: [
    { required: true, message: '请选择发票类型', trigger: 'change' }
  ],
  invoiceDate: [
    { required: true, message: '请选择开票日期', trigger: 'change' }
  ],
  sellerTaxNumber: [
    { required: true, message: '请输入销方识别号', trigger: 'blur' }
  ],
  sellerName: [
    { required: true, message: '请输入销方名称', trigger: 'blur' }
  ],
  buyerTaxNumber: [
    { required: true, message: '请输入购方识别号', trigger: 'blur' }
  ],
  buyerName: [
    { required: true, message: '请输入购方名称', trigger: 'blur' }
  ],
  totalAmount: [
    { required: true, message: '请输入金额', trigger: 'blur' }
  ],
  taxAmount: [
    { required: true, message: '请输入税额', trigger: 'blur' }
  ],
  totalTaxAmount: [
    { required: true, message: '请输入价税合计', trigger: 'blur' }
  ]
}

// 取消
const handleCancel = () => {
  emit('cancel')
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      loading.value = true
      try {
        // 确保isRedInvoice字段符合类型要求
        const submitData: any = {
          ...formData,
          isRedInvoice: formData.isRedInvoice === 'Y' ? 'Y' : 'N'
        }
        
        let response
        if (props.operation === 'add') {
          // 新增发票
          response = await createIncomingInvoice(submitData)
        } else {
          // 编辑发票
          response = await updateIncomingInvoice(formData.id, submitData)
        }
        
        if (response) {
          ElMessage.success(`${props.operation === 'add' ? '新增' : '更新'}进项发票成功`)
          emit('save-success')
        } else {
          ElMessage.error(`${props.operation === 'add' ? '新增' : '更新'}进项发票失败`)
        }
      } catch (error: any) {
        ElMessage.error(`${props.operation === 'add' ? '新增' : '更新'}进项发票失败: ${error.message || '未知错误'}`)
      } finally {
        loading.value = false
      }
    }
  })
}

// 组件挂载时获取数据
onMounted(async () => {
  // 根据操作类型和发票ID获取数据
  if (props.operation === 'edit' || props.operation === 'view') {
    if (props.invoiceId) {
      loading.value = true
      try {
        // 调用后端API获取发票详情
        const data: any = await getIncomingInvoiceById(props.invoiceId)
        Object.assign(formData, data)
        isEdit.value = true
      } catch (error: any) {
        ElMessage.error('获取发票详情失败: ' + (error.message || '未知错误'))
      } finally {
        loading.value = false
      }
    }
  }
})
</script>

<style scoped>
.invoice-edit-container {
  padding: 20px;
  height: calc(100vh - 60px);
  overflow-y: auto;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding: 20px 0;
}
</style>